<template>
  <div class="bookcontiner">
    <!-- 标题栏目 -->
    <div class="booktop">
      <div class="bookback" v-if="!checkshow" @click="backan"
        ><van-icon name="arrow-left"
      /></div>
      <div class="bookbacks" v-else @click="del">删除</div>

      <div class="bookname"
        >书签 <div class="casetotal">{{ imessagetotal }}</div></div
      >
      <div class="selcetboximg bookselect" @click="checkshow = !checkshow">
        <img src="@/assets/images/edit-1.png" alt="" />
        {{ checkshow ? '取消' : '编辑' }}
      </div>
    </div>
    <!-- 主体内容栏目 -->
    <div class="bookmain">
      <div class="searchbox">
        <!-- <van-search
          v-model="medicineAtlasName"
          shape="round"
          background="transparent"
          placeholder="请输入搜索关键词"
          @clear="reset"
        >
          <template #right-icon>
            <div @click="onRefresh()" style="color: black"
              >搜索&nbsp;&nbsp;</div
            >
          </template>
        </van-search>
        <div class="restbox" @click="reset">重 置</div> -->
      </div>
      <div
        class="book beautifulScroll"
        @scroll="handleScroll"
        ref="scrollContainer"
      >
        <van-checkbox-group v-model="checked">
          <div class="bookitem" v-for="item in renderData">
            <van-checkbox
              class="sediy"
              :name="item.bookMarkId"
              v-if="checkshow"
              checked-color="#5f6d7c"
            ></van-checkbox>
            <div class="bookitemimg" @click="gosq(item)">
              <img :src="`${base + item.url}`" alt="" />
            </div>
            <div class="bookitemdes" @click="gosq(item)">
              <div class="bookitemname">{{ item.medicineAtlasName }}</div>
              <div class="bookitemnames"></div>
            </div>
          </div>
        </van-checkbox-group>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { onBeforeUnmount, onMounted, reactive, ref } from 'vue';
  import { bookMarkList, bookMarkDel } from '@/api/bookMark';
  import { Pagination } from '@/types/global';
  import { storeToRefs } from 'pinia';
  import { useUserStore } from '@/store';
  import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant';
  const userStore = useUserStore();
  const userdata = storeToRefs(userStore);
  const studentId = ref(userdata.studentId.value);
  const medicineAtlasName = ref();
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const del = () => {
    if (checked.value.length <= 0) {
      showFailToast('请先选中标签');
      return;
    }

    // 调用确认对话框
    showConfirmDialog({
      title: '',
      message: '将选中的书签删除？',
      beforeClose,
    })
      .then(() => {
        console.log('对话框关闭后确认操作执行');
      })
      .catch(() => {
        console.log('对话框被取消或关闭被拦截');
      });
  };
  // 定义异步拦截逻辑，明确返回 Promise<boolean>
  // 定义异步拦截逻辑，明确返回 Promise<boolean>
  const beforeClose = (action: string): Promise<boolean> => {
    return new Promise<boolean>((resolve) => {
      if (action === 'confirm') {
        let bookMarkIds;
        if (checked.value.length > 1) {
          bookMarkIds = checked.value.join(',');
        }
        if (checked.value.length == 1) {
          bookMarkIds = checked.value[0];
        }
        bookMarkDel({ bookMarkIds: bookMarkIds }).then((res: any) => {
          if (res.code == 200) {
            showSuccessToast('删除成功');
            onRefresh();
          } else {
            showFailToast('删除失败');
          }
        });
        console.log('用户确认操作');
        resolve(true); // 确认时关闭对话框
      } else if (action === 'cancel') {
        console.log('用户取消操作');
        resolve(true); // 取消时也关闭对话框
      } else {
        resolve(false); // 其他情况下，不关闭对话框
      }
    });
  };
  const checkshow = ref(false);
  const checked = ref([]);
  const base = ref((window as any).config.VUE_APP_IMG_API);
  const imessagetotal = ref();
  const renderData = ref([]); // 渲染的数据列表
  // 请求数据方法
  const fetchData = async (isRefresh = false) => {
    try {
      const res = await bookMarkList({
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        studentId: studentId.value,
      });
      const newData = res.data.list || [];
      if (isRefresh) {
        renderData.value = newData; // 刷新时替换数据
      } else {
        renderData.value = [...renderData.value, ...newData]; // 加载更多时追加数据
      }
      finished.value = true; // 检查是否加载完成
      imessagetotal.value = res.data.list.length;
    } finally {
      // console.log('加载完成了吗', loading.value);
    }
  };
  const pagination = reactive({ ...basePagination });
  // 下拉刷新逻辑
  const onRefresh = async () => {
    pagination.current = 1; // 重置页码
    await fetchData(true); // 刷新数据
    isRefreshing.value = false;
  };
  // 清空搜撒
  const reset = () => {
    medicineAtlasName.value = '';
    onRefresh();
  };
  // 触底加载逻辑
  const onLoadMore = async () => {
    if (finished.value) return;
    pagination.current += 1;
    await fetchData(); // 加载更多数据
    isLoading.value = false;
  };
  //  滚动判断
  const scrollContainer = ref<HTMLElement | null>(null);
  const isRefreshing = ref(false);
  const isLoading = ref(false);
  const finished = ref(false);
  let startY = 0; // 记录触摸开始的位置
  let startX = 0; // 记录触摸开始的横向位置
  let isVerticalScroll = false; // 是否为垂直滚动

  // 下拉刷新处理
  const handleTouchStart = (event: TouchEvent) => {
    startY = event.touches[0].clientY;
    startX = event.touches[0].clientX;
    isVerticalScroll = false; // 重置滚动方向
  };

  let debounceTimeout: ReturnType<typeof setTimeout>;

  const handleTouchMove = (event: TouchEvent) => {
    const moveY = event.touches[0].clientY;
    const moveX = event.touches[0].clientX;
    const diffY = Math.abs(moveY - startY);
    const diffX = Math.abs(moveX - startX);

    // 判断是否为垂直滚动（如果垂直位移大于水平位移）
    if (!isVerticalScroll && diffY > diffX) {
      isVerticalScroll = true;
    }

    if (!isVerticalScroll) {
      // 如果不是垂直滚动，直接返回
      return;
    }

    if (scrollContainer.value && scrollContainer.value.scrollTop > 0) {
      return; // 如果不是在顶部，则不处理下拉刷新
    }

    clearTimeout(debounceTimeout); // 清除上一次的定时器
    debounceTimeout = setTimeout(() => {
      if (moveY - startY > 50 && !isRefreshing.value) {
        // 判断下拉超过50px
        isRefreshing.value = true;
        onRefresh();
      }
    }, 300); // 防抖：300ms
  };

  const handleTouchEnd = () => {
    startY = 0; // 清除触摸开始位置
    startX = 0; // 清除横向触摸开始位置
    isVerticalScroll = false; // 重置方向标志
    if (isRefreshing.value) {
      console.log('刷新已完成');
    }
  };

  // 触底加载处理
  let lastScrollTime = 0;

  const handleScroll = (event: Event) => {
    if (isRefreshing.value) return; // 正在刷新时，不触发触底加载
    const now = Date.now();
    if (now - lastScrollTime > 300) {
      lastScrollTime = now;
      const container = event.target as HTMLElement;
      if (
        container.scrollTop + container.clientHeight >=
          container.scrollHeight - 100 &&
        !isLoading.value
      ) {
        if (finished.value) return;
        isLoading.value = true;
        console.log('触底了');
        onLoadMore();
      }
    }
  };

  // 绑定触摸事件
  const bindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.addEventListener('touchstart', handleTouchStart);
      scrollContainer.value.addEventListener('touchmove', handleTouchMove);
      scrollContainer.value.addEventListener('touchend', handleTouchEnd);
    }
  };

  // 清除触摸事件
  const unbindTouchEvents = () => {
    if (scrollContainer.value) {
      scrollContainer.value.removeEventListener('touchstart', handleTouchStart);
      scrollContainer.value.removeEventListener('touchmove', handleTouchMove);
      scrollContainer.value.removeEventListener('touchend', handleTouchEnd);
    }
  };

  // 生命周期钩子：组件卸载时清除事件
  onBeforeUnmount(() => {
    unbindTouchEvents();
  });
  // 初始加载
  onMounted(() => {
    fetchData();
    bindTouchEvents();
  });

  // 滚动判断逻辑完成
  import { useRouter } from 'vue-router';
  const router = useRouter();
  const backan = () => {
    router.push({
      name: 'user',
    });
  };

  // 走图谱闲情
  const gosq = (item) => {
    localStorage.setItem('dcomid', item.medicineAtlasImgId);
    router.push({
      name: 'dashboardindex',
      query: {
        medicineAtlasId: item.medicineAtlasId,
        medicineAtlasName: item.medicineAtlasName,
        atlasTypeName: item.atlasTypeName,
      },
    });
  };
</script>

<style scoped>
  .book {
    display: flex;
    flex-direction: column;
    align-items: center;

    height: 90%;
    overflow-y: auto;
    padding-bottom: 150px;
  }
  .bookitem {
    width: 630px;
    height: 199px;
    background: #eef1f4;
    border-radius: 10px 10px 10px 10px;
    margin: 10px 0;
    display: flex;
    align-items: center;
    padding: 0px 10px;
  }
  .bookitemdes {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 10px;
  }
  .bookitemname {
    font-size: 30px;
  }
  .bookitemimg {
    width: 170px;
    height: 171px;
    overflow: hidden;
    border-radius: 10px;
  }
  .bookitemimg img {
    width: 170px;
    height: 171px;
  }
  .searchbox {
    display: flex;
    align-items: center;
    padding-right: 10px;
  }
  .bookmain {
    width: 690px;
    height: 92%;
    background: #ffffff;
    border-radius: 20px 20px 20px 20px;
    border: 1px solid rgba(153, 153, 153, 0.5);
    margin: 0 auto;
  }
  .bookcontiner {
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg, #5f6d7c 0%, #f4f4f4 25%);
    position: absolute;
    top: 0px;
    left: 0px;
  }
  .booktop {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30px 0;
    font-size: 32px;
    color: #ffff;
    position: relative;
    top: 0px;
    left: 0;
  }
  .bookback {
    font-size: 36px;
    color: #ffff;
    position: absolute;
    left: 20px;
  }
  .bookbacks {
    font-size: 30px;
    color: #ffff;
    position: absolute;
    left: 20px;
  }
  .bookname {
    display: flex;
    align-items: center;
  }
  .bookselect {
    position: absolute;
    right: 25px;
    font-size: 30px;
    color: #ffff;
  }
  .bookselect img {
    width: 24px;
    height: 24px;
  }
  .restbox {
    width: 114px;
    height: 70px;
    background: #5f6d7c;
    border-radius: 61px 61px 61px 61px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26px;
    color: #fff;
  }
  .casetotal {
    width: 29px;
    height: 29px;
    background: #ffffff;
    border-radius: 50%;
    align-items: center;
    display: flex;
    justify-content: center;
    color: #53606f;
    font-size: 18px;
    margin: 0px 10px;
  }
  .sediy {
    margin-right: 10px;
  }
</style>
